package io.renren.modules.substation.controller;

import com.alibaba.fastjson.JSONArray;
import io.renren.common.exception.RRException;
import io.renren.common.utils.CsvtojsonUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.substation.entity.TBusiLinkageLogEntity;
import io.renren.modules.substation.entity.TBusiSysAlarmInfoEntity;
import io.renren.modules.substation.entity.TInfoBackupConfigEntity;
import io.renren.modules.substation.service.TBusiLinkageLogService;
import io.renren.modules.substation.service.TBusiSysAlarmInfoService;
import io.renren.modules.substation.service.TInfoBackupConfigService;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.sys.entity.SysLogEntity;
import io.renren.modules.sys.entity.SysMenuEntity;
import io.renren.modules.sys.service.SysLogService;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.DataFormatException;

/**
 * 数据备份配置表
 *
 * @author yzx
 * @email sunlightcs@gmail.com
 * @date 2020-06-24 16:52:43
 */
@RestController
@RequestMapping("substation/tinfobackupconfig")
public class TInfoBackupConfigController extends AbstractController {
    private static Logger logger = LoggerFactory.getLogger(TInfoBackupConfigController.class);
    public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    @Autowired
    private TInfoBackupConfigService tInfoBackupConfigService;
    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private TBusiSysAlarmInfoService TBusiSysAlarmInfoService;
    @Autowired
    private TBusiLinkageLogService tBusiLinkageLogService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("substation:tinfobackupconfig:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = tInfoBackupConfigService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/listall")
//    @RequiresPermissions("substation:tinfobackupconfig:listall")
    public R listall(){

        List<TInfoBackupConfigEntity> list = tInfoBackupConfigService.list();

        return R.ok().put("list", list);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("substation:tinfobackupconfig:info")
    public R info(@PathVariable("id") Long id){
		TInfoBackupConfigEntity tInfoBackupConfig = tInfoBackupConfigService.getById(id);

        return R.ok().put("tInfoBackupConfig", tInfoBackupConfig);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("substation:tinfobackupconfig:save")
    public R save(@RequestBody TInfoBackupConfigEntity tInfoBackupConfig){
		tInfoBackupConfigService.save(tInfoBackupConfig);

        return R.ok();
    }

    /**
     * 所有菜单列表
     */
    @GetMapping("/listallmenu")
//    @RequiresPermissions("substation:tinfobackupconfig:listallmenu")
    public R list(){
//        List<TInfoBackupConfigEntity>
        List<TInfoBackupConfigEntity> menuList = tInfoBackupConfigService.list();
        for(TInfoBackupConfigEntity sysMenuEntity : menuList){
            TInfoBackupConfigEntity parentMenuEntity = tInfoBackupConfigService.getById(sysMenuEntity.getConfigContentId());
            if(parentMenuEntity != null){
                sysMenuEntity.setParentName(parentMenuEntity.getConfigConten());
            }
//            logger.debug("menuList:" + parentMenuEntity);
        }
        logger.debug("menuList:" + menuList);
        List<TInfoBackupConfigEntity> menuListTree = menuList.stream()
                .filter(menu->menu.getConfigType().equals("0")).map(menu->{
                    menu.setListTree(getChildren(menu, menuList));
                    return menu;
                }).collect(Collectors.toList());

        logger.debug("menuListTree:" + menuListTree);

        return R.ok().put("menuListTree",menuListTree);
    }

    /**
     * 递归获取子菜单
     * @param root 当前菜单
     * @param all 总的数据
     * @return 子菜单
     */
    public List<TInfoBackupConfigEntity> getChildren(TInfoBackupConfigEntity root, List<TInfoBackupConfigEntity> all) {
        List<TInfoBackupConfigEntity> children = all.stream()
                // 根据 父菜单 ID 查找当前菜单 ID，以便于找到 当前菜单的子菜单
                .filter(menu -> menu.getConfigContentId() == root.getId())
                // 递归查找子菜单的子菜单
                .map((menu) -> {
                    menu.setListTree(getChildren(menu, all));
                    return menu;
                })
                // 根据排序字段排序
//                .sorted((menu1, menu2) -> {
//                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
//                })
                // 把处理结果收集成一个 List 集合
                .collect(Collectors.toList());
        return children;
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("substation:tinfobackupconfig:update")
    public R update(@RequestBody TInfoBackupConfigEntity tInfoBackupConfig){
        tInfoBackupConfigService.updateById(tInfoBackupConfig);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/updatevaild")
//    @RequiresPermissions("substation:tinfobackupconfig:updatevaild")
    public R updatevaild(@RequestBody Long[] menuIdList){

//        logger.debug("tInfoBackupConfig:"+tInfoBackupConfig);
//        ValidatorUtils.validateEntity(tInfoBackupConfig);
        logger.debug("menuIdList:"+menuIdList);
        TInfoBackupConfigEntity tt=new TInfoBackupConfigEntity();
        tt.setIsVaild("0");
//        tt.setId((long)id);
        tt.setLastTime(new Date());
        int updsum = tInfoBackupConfigService.updateAllIsvaild(tt);
        logger.debug("updateAllIsvaild count:"+updsum);
//        List<Long> list = tInfoBackupConfig.getMenuIdList();
        for(int i=0;i<menuIdList.length;i++){
//            tInfoBackupConfigService.update();
//            tInfoBackupConfigService.updateById(tInfoBackupConfig);
            TInfoBackupConfigEntity tInfoBackupConfigEntity = new TInfoBackupConfigEntity();
            tInfoBackupConfigEntity.setId(menuIdList[i]);
            tInfoBackupConfigEntity.setIsVaild("1");
            tInfoBackupConfigService.updateById(tInfoBackupConfigEntity);
        }



        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("substation:tinfobackupconfig:delete")
    public R delete(@RequestBody Long[] ids){
		tInfoBackupConfigService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    @PostMapping("/upload")
//    @RequiresPermissions("substation:tinfobackupconfig:upload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {

        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        logger.debug("文件长度:" + file.getSize());
        logger.debug("" + file.getOriginalFilename());
        logger.debug("" + file.getName());
        logger.debug("" + file.getContentType());
        logger.debug("" + file.getResource());
//        String fileName = file.getName();
//        String path = file.getResource();
//        //这里我试了，可以用 fileName   也可以用  OriginalFilename   都没问题的
//        File f = new File(new File(path).getAbsolutePath()+ "/" + fileName);
//        file.transferTo(f);
        logger.debug("文件名:" + file.getOriginalFilename());
        if (file.getOriginalFilename().indexOf("日志列表") >= 0)
        {
            try {
                JSONArray jsonArray = CsvtojsonUtils.readLogCsvToJsonArr(file);
                logger.debug("这是日志文件数据导入:" + jsonArray.toString());
                SysLogEntity sysLog = new SysLogEntity();
                for(int i=0;i<jsonArray.size();i++) {
                    logger.debug("第" + i + "记录");
    //                logger.debug(jsonArray.getJSONObject(i).get("id"));
    //                jsonArray.getJSONObject(i).getString();
                    logger.debug(jsonArray.getJSONObject(i).getString("id"));
                    logger.debug(jsonArray.getJSONObject(i).getString("用户名"));
                    logger.debug(jsonArray.getJSONObject(i).getString("用户操作"));
                    logger.debug(jsonArray.getJSONObject(i).getString("请求方法"));
                    logger.debug(jsonArray.getJSONObject(i).getString("请求参数"));
                    sysLog.setUsername(jsonArray.getJSONObject(i).getString("用户名"));
                    sysLog.setOperation(jsonArray.getJSONObject(i).getString("用户操作"));
                    sysLog.setMethod(jsonArray.getJSONObject(i).getString("请求方法"));
                    sysLog.setParams(jsonArray.getJSONObject(i).getString("请求参数"));
                    sysLog.setParams("null");
                    Long.valueOf(jsonArray.getJSONObject(i).getString("执行时长(毫秒)"));
                    logger.debug("执行时长:" + Long.valueOf(jsonArray.getJSONObject(i).getString("执行时长(毫秒)")));
                    sysLog.setTime(Long.valueOf(jsonArray.getJSONObject(i).getString("执行时长(毫秒)")));
                    sysLog.setIp(jsonArray.getJSONObject(i).getString("ip地址"));
                    sysLog.setCreateDate(sdf.parse(jsonArray.getJSONObject(i).getString("创建时间")));
                    sysLogService.save(sysLog);
                }
            } catch (Exception e) {
                throw new RRException("上传文件失败，请检查文件", e);
            }
        }
        else if(file.getOriginalFilename().indexOf("局放数据列表") >= 0)
        {
            logger.debug("局放数据列表:" + file.getOriginalFilename());
            try{
                JSONArray jsonArray = CsvtojsonUtils.readLogCsvToJsonArr(file);
                logger.debug("这是局放数据导入:" + jsonArray.toString());
//                SysLogEntity sysLog = new SysLogEntity();
                for(int i=0;i<jsonArray.size();i++) {
                    logger.debug("第" + i + "记录");
                    //                logger.debug(jsonArray.getJSONObject(i).get("id"));
                    //                jsonArray.getJSONObject(i).getString();
                    logger.debug(jsonArray.getJSONObject(i).getString("记录号"));
                    logger.debug(jsonArray.getJSONObject(i).getString("基本信息"));
                    logger.debug(jsonArray.getJSONObject(i).getString("设备名称"));
                    logger.debug(jsonArray.getJSONObject(i).getString("局放"));
                    logger.debug(jsonArray.getJSONObject(i).getString("红外热像"));
                    logger.debug(jsonArray.getJSONObject(i).getString("可见光图片"));
                    logger.debug(jsonArray.getJSONObject(i).getString("噪声"));
                    logger.debug(jsonArray.getJSONObject(i).getString("温湿度"));
//                    sysLog.setUsername(jsonArray.getJSONObject(i).getString("用户名"));
//                    sysLog.setOperation(jsonArray.getJSONObject(i).getString("用户操作"));
//                    sysLog.setMethod(jsonArray.getJSONObject(i).getString("请求方法"));
//                    sysLog.setParams(jsonArray.getJSONObject(i).getString("请求参数"));
//                    sysLog.setParams("null");
//                    Long.valueOf(jsonArray.getJSONObject(i).getString("执行时长(毫秒)"));
//                    logger.debug("执行时长:" + Long.valueOf(jsonArray.getJSONObject(i).getString("执行时长(毫秒)")));
//                    sysLog.setTime(Long.valueOf(jsonArray.getJSONObject(i).getString("执行时长(毫秒)")));
//                    sysLog.setIp(jsonArray.getJSONObject(i).getString("ip地址"));
//                    sysLog.setCreateDate(sdf.parse(jsonArray.getJSONObject(i).getString("创建时间")));
//                    sysLogService.save(sysLog);
                }
            } catch (Exception e) {
                throw new RRException("上传文件失败，请检查文件", e);
            }
        }
        else if(file.getOriginalFilename().indexOf("动力数据列表") >= 0)
        {
            logger.debug("动力数据列表:" + file.getOriginalFilename());
            try{
                JSONArray jsonArray = CsvtojsonUtils.readLogCsvToJsonArr(file);
                logger.debug("这是动力数据导入:" + jsonArray.toString());
//                SysLogEntity sysLog = new SysLogEntity();
                for(int i=0;i<jsonArray.size();i++) {
                    logger.debug("第" + i + "记录");
                    //                logger.debug(jsonArray.getJSONObject(i).get("id"));
                    //                jsonArray.getJSONObject(i).getString();
                    logger.debug(jsonArray.getJSONObject(i).getString("记录号"));
                    logger.debug(jsonArray.getJSONObject(i).getString("基本信息"));
                    logger.debug(jsonArray.getJSONObject(i).getString("设备名称"));
                    logger.debug(jsonArray.getJSONObject(i).getString("水位"));
                    logger.debug(jsonArray.getJSONObject(i).getString("烟感状态"));
                    logger.debug(jsonArray.getJSONObject(i).getString("红外三鉴状态"));
                    logger.debug(jsonArray.getJSONObject(i).getString("灯光控制开关状态"));
                    logger.debug(jsonArray.getJSONObject(i).getString("温湿度"));
//                    sysLog.setUsername(jsonArray.getJSONObject(i).getString("用户名"));
//                    sysLog.setOperation(jsonArray.getJSONObject(i).getString("用户操作"));
//                    sysLog.setMethod(jsonArray.getJSONObject(i).getString("请求方法"));
//                    sysLog.setParams(jsonArray.getJSONObject(i).getString("请求参数"));
//                    sysLog.setParams("null");
//                    Long.valueOf(jsonArray.getJSONObject(i).getString("执行时长(毫秒)"));
//                    logger.debug("执行时长:" + Long.valueOf(jsonArray.getJSONObject(i).getString("执行时长(毫秒)")));
//                    sysLog.setTime(Long.valueOf(jsonArray.getJSONObject(i).getString("执行时长(毫秒)")));
//                    sysLog.setIp(jsonArray.getJSONObject(i).getString("ip地址"));
//                    sysLog.setCreateDate(sdf.parse(jsonArray.getJSONObject(i).getString("创建时间")));
//                    sysLogService.save(sysLog);
                }
            } catch (Exception e) {
                throw new RRException("上传文件失败，请检查文件", e);
            }
        }
        else if (file.getOriginalFilename().indexOf("告警列表") >= 0)
        {
            logger.debug("告警列表:" + file.getOriginalFilename());
            try{
                JSONArray jsonArray = CsvtojsonUtils.readLogCsvToJsonArr(file);
                logger.debug("这是告警数据导入:" + jsonArray.toString());
                TBusiSysAlarmInfoEntity tBusiSysAlarmInfoEntity = new TBusiSysAlarmInfoEntity();
                for(int i=0;i<jsonArray.size();i++) {
                    logger.debug("第" + i + "记录");
                    //                logger.debug(jsonArray.getJSONObject(i).get("id"));
                    //                jsonArray.getJSONObject(i).getString();
                    logger.debug(jsonArray.getJSONObject(i).getString("告警时间"));
                    logger.debug(jsonArray.getJSONObject(i).getString("站址"));
                    logger.debug(jsonArray.getJSONObject(i).getString("告警源"));
                    logger.debug(jsonArray.getJSONObject(i).getString("告警类型"));
                    logger.debug(jsonArray.getJSONObject(i).getString("告警描述"));

                    tBusiSysAlarmInfoEntity.setAlarmTime(jsonArray.getJSONObject(i).getString("告警时间"));
                    tBusiSysAlarmInfoEntity.setAreaAddr(jsonArray.getJSONObject(i).getString("站址"));
                    tBusiSysAlarmInfoEntity.setAlarmSource(jsonArray.getJSONObject(i).getString("告警源"));
                    tBusiSysAlarmInfoEntity.setAlarmType(jsonArray.getJSONObject(i).getString("告警类型"));
                    tBusiSysAlarmInfoEntity.setAlarmDesc(jsonArray.getJSONObject(i).getString("告警类型"));

                    tBusiSysAlarmInfoEntity.setAlarmArea((long) 0);//告警区域
                    tBusiSysAlarmInfoEntity.setAlarmLevel((long) 0);
                    tBusiSysAlarmInfoEntity.setCreateOpr(getUserId());
                    tBusiSysAlarmInfoEntity.setLastOpr(getUserId());
                    tBusiSysAlarmInfoEntity.setLastTime(new Date());
                    tBusiSysAlarmInfoEntity.setCreateTime(new Date());
//                    Long.valueOf(jsonArray.getJSONObject(i).getString("执行时长(毫秒)"));
//                    logger.debug("执行时长:" + Long.valueOf(jsonArray.getJSONObject(i).getString("执行时长(毫秒)")));
//                    sysLog.setTime(Long.valueOf(jsonArray.getJSONObject(i).getString("执行时长(毫秒)")));
//                    sysLog.setIp(jsonArray.getJSONObject(i).getString("ip地址"));
//                    sysLog.setCreateDate(sdf.parse(jsonArray.getJSONObject(i).getString("创建时间")));
                    TBusiSysAlarmInfoService.save(tBusiSysAlarmInfoEntity);
                }
            } catch (Exception e) {
                throw new RRException("上传文件失败，请检查文件", e);
            }
        }
        else if (file.getOriginalFilename().indexOf("联动列表") >= 0)
        {
            logger.debug("联动列表:" + file.getOriginalFilename());
            try{
                JSONArray jsonArray = CsvtojsonUtils.readLogCsvToJsonArr(file);
                logger.debug("这是联动数据导入:" + jsonArray.toString());
                TBusiLinkageLogEntity tBusiLinkageLogEntity = new TBusiLinkageLogEntity();
                for(int i=0;i<jsonArray.size();i++) {
                    logger.debug("第" + i + "记录");
                    //                logger.debug(jsonArray.getJSONObject(i).get("id"));
                    //                jsonArray.getJSONObject(i).getString();
                    logger.debug(jsonArray.getJSONObject(i).getString("联动记录序列号"));
                    logger.debug(jsonArray.getJSONObject(i).getString("联动执行时间"));
                    logger.debug(jsonArray.getJSONObject(i).getString("联动执行条件"));
                    logger.debug(jsonArray.getJSONObject(i).getString("联动触发条件"));
                    logger.debug(jsonArray.getJSONObject(i).getString("执行内容"));

                    tBusiLinkageLogEntity.setLinkageTime(jsonArray.getJSONObject(i).getString("联动执行时间"));
                    tBusiLinkageLogEntity.setPerformConditions(jsonArray.getJSONObject(i).getString("联动执行条件"));
                    tBusiLinkageLogEntity.setTriggerConditions(jsonArray.getJSONObject(i).getString("联动触发条件"));
                    tBusiLinkageLogEntity.setPerformContent(jsonArray.getJSONObject(i).getString("执行内容"));
//                    tBusiLinkageLogEntity.setAlarmDesc(jsonArray.getJSONObject(i).getString("告警类型"));

                    tBusiLinkageLogEntity.setCreateOpr(getUserId());
                    tBusiLinkageLogEntity.setLastOpr(getUserId());
                    tBusiLinkageLogEntity.setLastTime(new Date());
                    tBusiLinkageLogEntity.setCreateTime(new Date());
//                    Long.valueOf(jsonArray.getJSONObject(i).getString("执行时长(毫秒)"));
//                    logger.debug("执行时长:" + Long.valueOf(jsonArray.getJSONObject(i).getString("执行时长(毫秒)")));
//                    sysLog.setTime(Long.valueOf(jsonArray.getJSONObject(i).getString("执行时长(毫秒)")));
//                    sysLog.setIp(jsonArray.getJSONObject(i).getString("ip地址"));
//                    sysLog.setCreateDate(sdf.parse(jsonArray.getJSONObject(i).getString("创建时间")));
                    tBusiLinkageLogService.save(tBusiLinkageLogEntity);
                }
            } catch (Exception e) {
                throw new RRException("上传文件失败，请检查文件", e);
            }
        }
        else
        {
            logger.debug("其他文件导入:" + file.getOriginalFilename());
            throw new RRException("文件上传失败，文件名不符");
        }

        //上传文件
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//        String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);
//        logger.debug("这是一串测试url：" + url.toString());
        String url = "上传文件成功";
        //保存文件信息
//        SysOssEntity ossEntity = new SysOssEntity();
//        ossEntity.setUrl(url);
//        ossEntity.setCreateDate(new Date());
//        sysOssService.save(ossEntity);

        return R.ok().put("url", url);
    }

    @RequestMapping("/export")
//    @RequiresPermissions("substation:tinfobackupconfig:importlog")
    public ResponseEntity exportLog(HttpServletResponse response, @RequestParam Map<String, Object> map) throws UnsupportedEncodingException, FileNotFoundException {


//        final List<UserEmailDetailVO> vos = userInfoService.getAllFiltrationUsersEmail(map);
        PageUtils page = sysLogService.queryPage(map);

        // 获取数据response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");

        // 下载文件能正常显示中文
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(map.get("exportFileName").toString() + ".csv", "UTF-8"));

        CSVFormat csvFormat = CSVFormat.EXCEL.
                withHeader("id","username","operation","method","params","time","ip","createDate");

        try {
            CSVPrinter csvPrinter = new CSVPrinter(response.getWriter(), csvFormat);
            List<SysLogEntity> sysLogEntityList = (List<SysLogEntity>) page.getList();
            for (SysLogEntity vo : sysLogEntityList) {
                if (Objects.nonNull(vo) && !"".equals(vo.getUsername())) {

                    csvPrinter.printRecord(vo.getId(), vo.getUsername(),vo.getOperation(),vo.getMethod(),vo.getParams(),vo.getTime(),vo.getIp(),vo.getCreateDate());
                }
            }

            csvPrinter.flush();
            csvPrinter.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }

        return ResponseEntity.ok().build();
    }
}
